﻿import com.gamemeal.mvc.IDataHandler;
import com.gamemeal.mvc.IView;
import com.gamemeal.mvc.datatype.MFObject;

/**
 * @author Colin
 */
class com.gamemeal.mvc.ViewDataHandler implements IDataHandler {
	private var successor : IDataHandler;
	private var view:IView;
	
	public function ViewDataHandler(view:IView){
		this.view = view;
		if(view==undefined)throw new Error('ViewDataHandler need view in constructor');
	}

	public function getValue(modelField : MFObject):Object{
		var bindMap = view.getValue();
		var viewValue:Object;
		for(var i=0;i<bindMap.length;i++){
			if(bindMap[i].bind===modelField)viewValue = bindMap[i].view.value;
		}
		if(viewValue!=undefined){
			return viewValue;
		}else if(successor!=undefined){
			successor.getValue(modelField);
		}else{
			throw new Error('Data Field Not Found');
		}
	}

	public function setValue(modelField : MFObject, value : Object):Void {
		var bindMap = view.getValue();
		for(var i=0;i<bindMap.length;i++){
			if(bindMap[i].bind===modelField){
				bindMap[i].view.value = value;
			}
		}
	}

	public function setSuccessor(h : IDataHandler) : Void {
		successor = h;
	}
}